import { Md5 } from "ts-md5";
function getRandomNumber(): number {
  return Math.floor(1000 + Math.random() * 9000);
}

function getTime(){
  return parseInt(String(Date.now() / 1000));
}

function getAppKey(){
  return "U8exRs";
}

function getAppSecret(){
  return "LocY2OHBxk0uJs";
}

function makeSign(data) {
  const t = getTime();
  const r = getRandomNumber();
  const d = JSON.stringify(sortASCII(data, true));
  const k = getAppKey();
  const secret = getAppSecret();
  //console.log(d + k + secret + t + r);
  const sign = Md5.hashStr(d + k + secret + t + r);
  return {
    k: k,
    t: t,
    r: r,
    sign: sign,
	'Content-Type': 'application/json',
  };
}

function sortASCII(obj:any, isSort:any) {
  const arr = [];
  Object.keys(obj).forEach(item => arr.push(item))
  const sortArr = isSort ? arr.sort() : arr.sort().reverse();
  const sortObj = {};
  for (const i in sortArr) {
    sortObj[sortArr[i]] = obj[sortArr[i]];
  }
  return sortObj;
}

export default makeSign;